import axios from 'axios'
import qs from 'qs'
import apis from './apis'
import { ElLoading, ElMessage } from 'element-plus'
import router from '../router/index'

let loading = null

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
	loading = ElLoading.service({
		lock: true,
		text: '请稍等，玩命加载中...',
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.7)'
	})
	config.url = apis.get(config.url) ? apis.get(config.url) : config.url
	return config
}, function (error) {
	loading.close()
	return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use((response) => {
	loading.close()
	if (response.data.status === 'err') {
		ElMessage.error(response.data.message)
	}
	return response
}, function (error) {
	loading.close()
	if (error && error.response) {
		switch (error.response.status) {
			case 401:
				error.message = '登录失效，请重新登录'
				router.replace('/login')
				break
			case 408:
				error.message = '请求超时，请重试'
				break
			case 504:
				error.message = '网络超时，请重试'
				break
			default:
				error.message = '处理失败，请重新登录后再试（错误代码：' + error.response.status + ')'
		}
	} else {
		error.message = '服务器连接失败，请检查网络后重试'
	}
	ElMessage.error(error.message)
	return Promise.reject(error)
})

export default {
	get (url, param) {
		return new Promise((resolve, reject) => {
			axios.get(url, param).then((res) => {
				resolve(res.data)
			}).catch((err) => {
				reject(err)
			})
		})
	},
	post (url, param) {
		return new Promise((resolve, reject) => {
			axios.post(url, qs.stringify(param)).then((res) => {
				if (res) resolve(res.data)
			}).catch((err) => {
				reject(err)
			})
		})
	},
	all (promises, callback) {
		axios.all(promises).then(() => {
			axios.spread(callback)
		})
	}
}
